package org.itboys.core.service.mongo.web;

import org.apache.commons.lang.StringUtils;
import org.itboys.admin.entity.lasted.SystemUser;
import org.itboys.admin.service.lasted.SystemUserService;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.encryption.Digests;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.core.common.ExceptionEnum;
import org.itboys.core.common.SundayCommonConstants;
import org.itboys.core.dao.wallet.SundayWalletMapper;
import org.itboys.core.entity.mongo.SundayMember;
import org.itboys.core.entity.mysql.wallet.SundayWallet;
import org.itboys.core.util.InviteCodeUtil;
import org.itboys.core.util.NameUtil;
import org.itboys.core.util.PhoneUtil;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author：贾琦磊
 * @Date：2018/11/26
 * @Description：
 */
@Service
public class SundayMemberService extends BaseMongoService<SundayMember> {
    @Resource(name = "mobileDs")
    private MongoDataSource sundayDataSource;
    @Autowired
    private ResourceHolder resourceHolder;
    @Autowired
    private SystemUserService userService;
    @Autowired
    private SundayWalletMapper walletMapper;

    @Override
    protected MongoDataSource getMongoDataSource() {
        return sundayDataSource;
    }

    @Override
    protected Class<SundayMember> getEntityClass() {
        return SundayMember.class;
    }

    /**
     * 分页获取用户信息信息
     *
     * @param request
     * @return
     */
    public PageResult<SundayMember> select(HttpServletRequest request) {
        Map<String, Object> param = ParamUtil.packageMongoExactParam(request, "userType");
        param.put("isDeleted", 0);
        Map<String, String> containsparam = ParamUtil.packageMongoVagueParam(request, "mobile", "realName");
        PageResult<SundayMember> result = super.containpageQuery(request, containsparam, param);
        return result;
    }

    @Override
    public void save(SundayMember member) {
        if (!PhoneUtil.isMobileNumber(member.getMobile()))
            throw new ErrorException(ExceptionEnum.MOBILE_FORMAT_ERROR.getValue());
        Map<String, Object> param = new HashMap<>();
        param.put("isDeleted", SundayCommonConstants.NO);
        param.put("mobile", member.getMobile());
        List<SundayMember> members = super.list(param);
        if (ListUtil.isNotNull(members) && member.getId() != members.get(0).getId()) {
            throw new ErrorException(ExceptionEnum.MOBILE_HAS_BEEN_REGISTERED.getValue());
        }
        String password = member.getPassword();
        if (StringUtils.isEmpty(password)) {
            password = "123456";
        }
        member.setPassword(Digests.md5(password));
        if (LongUtil.isNotZreo(member.getId())) {
            super.updateExceptEmpty(member.getId(), member);
        } else {
            member.setNickName("供应商-"+InviteCodeUtil.idToCode(super.iDGeneratorService.getNextId(SundayMember.class.getName())));
            member.setImage(NameUtil.getRandomLogo());
            SystemUser user = new SystemUser();
            user.setName(member.getRealName());
            user.setPassword(member.getPassword());
            user.setIsSuper(SundayCommonConstants.NO);
            user.setUserName(member.getMobile());
            user.setLogo(member.getImage());
            user.setStatus(SundayCommonConstants.NO);
            userService.save(user);
            super.save(member);
            SundayWallet wallet=new SundayWallet(member.getId(), BigDecimal.ZERO,BigDecimal.ZERO, BigDecimal.ZERO);
            walletMapper.insert(wallet);
        }
    }

    @Override
    public void delete(Long id) {
        SundayMember member = super.getById(id);
        Map<String, Object> param = new HashMap<>();
        param.put("userName", member.getMobile());
        userService.delete(param);
        super.delete(id);
    }

    public SundayMember getMemberByUserId(Long userId) {
        SystemUser user = userService.getById(userId);
        if (user == null) throw new ErrorException(ExceptionEnum.USER_NONENTITY.getValue());
        List<SundayMember> members = super.findByField("mobile", user.getUserName());
        if(ListUtil.isNotNull(members)) return members.get(0);
        return null;
    }
}
